import frappe
from frappe.model.utils import user_settings
from frappe import safe_decode

def patch_user_settings():
    """应用达梦数据库用户设置补丁"""
    
    def dm_sync_user_settings():
        """达梦数据库同步用户设置实现"""
        for key, data in frappe.cache.hgetall("_user_settings").items():
            key = safe_decode(key)
            doctype, user = key.split("::")
            
            # 达梦数据库使用MERGE INTO语法
            sql = """
                MERGE INTO "__UserSettings" t
                USING (
                    SELECT 
                        ? as "user",
                        ? as "doctype",
                        ? as "data"
                    FROM DUAL
                ) s
                ON (t."user" = s."user" AND t."doctype" = s."doctype")
                WHEN MATCHED THEN
                    UPDATE SET t."data" = s."data"
                WHEN NOT MATCHED THEN
                    INSERT ("user", "doctype", "data")
                    VALUES (s."user", s."doctype", s."data")
            """
            
            frappe.db.sql(sql, (user, doctype, data))
    
    def patched_sync_user_settings():
        """支持达梦数据库的用户设置同步方法"""
        if frappe.db.db_type == "dm":
            return dm_sync_user_settings()
            
        # 调用原始实现
        return user_settings._original_sync_user_settings()
    
    # 保存原始函数
    if not hasattr(user_settings, '_original_sync_user_settings'):
        user_settings._original_sync_user_settings = user_settings.sync_user_settings
    
    # 应用补丁
    user_settings.sync_user_settings = patched_sync_user_settings

def revert_user_settings_patches():
    """恢复用户设置相关的原始函数"""
    if hasattr(user_settings, '_original_sync_user_settings'):
        user_settings.sync_user_settings = user_settings._original_sync_user_settings
        del user_settings._original_sync_user_settings
